#include "compi/compi.h"

#include <iostream>
#include <mpi.h>
#include <vector>

using namespace compi;

int
main(int argc, char ** argv)
{
    Environment env(ThreadLevel::Multiple);
    Context & ctx = Context::for_comm(MPI_COMM_WORLD, env);

    const int world_size = ctx.size();
    const int world_rank = ctx.rank();

    // 构造一个简单的环形图邻接关系
    topology::GraphCreateParams params;
    params.index.resize(world_size);
    params.edges.resize(static_cast<std::size_t>(world_size) * 2);

    for (int i = 0; i < world_size; ++i)
    {
        int left = (i - 1 + world_size) % world_size;
        int right = (i + 1) % world_size;
        params.edges[static_cast<std::size_t>(i) * 2 + 0] = left;
        params.edges[static_cast<std::size_t>(i) * 2 + 1] = right;
        params.index[i] = (i + 1) * 2;
    }

    auto graph_res = topology::create_graph(ctx, params);
    if (graph_res.is_error())
    {
        if (world_rank == 0)
        {
            std::cerr << "Failed to create graph topology: " << graph_res.error_message() << std::endl;
        }
        return 1;
    }

    topology::TopologyHandle graph = std::move(graph_res).value();
    if (!graph.valid())
    {
        if (world_rank == 0)
        {
            std::cout << "Process excluded from graph communicator." << std::endl;
        }
        return 0;
    }

    auto neighbors_res = topology::graph_neighbors(graph);
    if (neighbors_res.is_error())
    {
        if (world_rank == 0)
        {
            std::cerr << "graph_neighbors failed: " << neighbors_res.error_message() << std::endl;
        }
        return 1;
    }

    const auto neighbors = neighbors_res.value();
    std::cout << "Rank " << world_rank << " neighbors: ";
    for (std::size_t i = 0; i < neighbors.size(); ++i)
    {
        std::cout << neighbors[i];
        if (i + 1 < neighbors.size())
            std::cout << ", ";
    }
    std::cout << std::endl;

    return 0;
}

